package com.zahidq.nio.test;


import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA.
 * User: Zahid
 * Date: 16/03/13
 * Time: 12:27
 * To change this template use File | Settings | File Templates.
 */
public class EchoServer implements Runnable {

    Logger logger = Logger.getLogger(EchoServer.class);

    private final boolean async;
    private final boolean useDirectByteBuffer;
    private final int byteBufferSize;
    private final int port;
    private final byte[] bytes;

    public EchoServer(boolean async, boolean useDirectByteBuffer, int byteBufferSize, int port) {
        logger.info("#EchoServer async="+async
                + " useDirectByteBuffer=" + useDirectByteBuffer
                + " byteBufferSize=" + byteBufferSize
                + " port=" + port);
        this.async = async;
        this.useDirectByteBuffer = useDirectByteBuffer;
        this.byteBufferSize = byteBufferSize;
        this.port = port;
        if (useDirectByteBuffer) {
            bytes = new byte[byteBufferSize];
        } else {
            bytes = null;
        }
    }

    @Override
    public void run() {
        logger.info("#run");
        ByteBuffer byteBuffer = useDirectByteBuffer ? ByteBuffer.allocateDirect(byteBufferSize) : ByteBuffer.allocate(byteBufferSize);

        if (async) {
            try {
                AsynchronousServerSocketChannel asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
                Future<AsynchronousSocketChannel> future = asynchronousServerSocketChannel.accept();
                AsynchronousSocketChannel worker = future.get();
                worker.setOption(StandardSocketOptions.TCP_NODELAY,true);
                do {
                    byteBuffer.clear();
                    worker.read(byteBuffer).get();
                    if (byteBuffer.position() > 0) {
                        byteBuffer.flip();
                        worker.write(byteBuffer).get();
                        byteBuffer.flip();
                    }
                } while (! Thread.currentThread().isInterrupted());
                worker.close();
                asynchronousServerSocketChannel.close();
            } catch (Exception e) {
                logger.error("#run caught: " + e.getMessage());
            }
        } else {
            try {
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open().bind(new InetSocketAddress(port));
                SocketChannel socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(true);
                socketChannel.setOption(StandardSocketOptions.TCP_NODELAY,true);
                do {
                    int read = socketChannel.read(byteBuffer);
                    if (read > 0) {
                        byteBuffer.flip();
                        socketChannel.write(byteBuffer);
                        byteBuffer.flip();
                    }
                } while ( ! Thread.currentThread().isInterrupted());
            } catch (IOException e) {
                logger.warn("#run caught" + e.getMessage());
            }

        }
        logger.info("#run finished");

    }
}
